package cn.aishu.anydream.service;

import cn.aishu.anydream.dao.UserMapper;
import cn.aishu.anydream.entity.User;
import cn.aishu.common.AishuException;
import cn.aishu.common.ResponseModel;
import cn.aishu.common.ToolBox;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "${aishu.web.path}", allowedHeaders = "*", allowCredentials = "true")
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/users/registry")
    public ResponseModel register(String userName, String passWord, String tel) {
        // 验证用户名、密码、手机号是否为空
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord) || StringUtils.isEmpty(tel)) {
            throw new AishuException("参数错误！");
        }

        // 验证用户名是否已被注册
        User user = userMapper.selectByUserName(userName);

        if (user != null) {
            throw new AishuException("用户名已被注册！");
        }

        // 验证手机号是否已被注册
        user = userMapper.selectByTel(tel);

        if (user != null) {
            throw new AishuException("手机号已被注册！");
        }

        // 进行密码加密
        // 生成User对象，存入数据库
        User newUser = new User();
        newUser.setUserName(userName);
        newUser.setPassword(ToolBox.md5(passWord));
        newUser.setTel(tel);

        userMapper.insertUser(newUser);

        String message = "注册成功！";

        // 返回消息
        return new ResponseModel(message);
    }
}
